using IStrong.EC.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
using IStrong.EC.ExtensionMethods;
using IStrong.EC.WebApi.Results.Entity;
using IStrong.EC.WebApi.Results.Enums;
using IStrong.EC.WebApi.Results.Repository;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json.Linq;

namespace IStrong.EC.WebApi.Results.Controllers
{
    /// <summary>
    /// Api控制器模板
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ChannelController : BaseController
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ChannelController> _logger;

        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration _config;
        /// <summary>
        /// 配置
        /// </summary>
        private readonly ChannelRepository _channelRepository;

        private readonly Utility _unitl;

        public readonly IHostingEnvironment _hostingEnvironment;

        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="config"></param>
        /// <param name="channelRepository"></param>
        public ChannelController(ILogger<ChannelController> logger, IConfiguration config, ChannelRepository channelRepository, IHostingEnvironment hostingEnvironment, Utility unitl)
        {
            _logger = logger;
            _config = config;
            _channelRepository = channelRepository;
            _hostingEnvironment = hostingEnvironment;
            _unitl = unitl;
        }

        [HttpGet]
        public JsonResult GetPagingList(
           string CustomName,
           string Company,
           string Province,
           string City,
           string ChannelCreator,
           string PricipalName,
           string SourceType,
           string Source,
           string ChannelType,
           int? Importance,
           int? Rate,
           string FollowFrequency,
           int PageSize = 50,
           int PageIndex = 1,
           string prop = "",
           string order = "")
        {
            try
            {
                string OrderStr = null;

                if (prop != "")
                {
                    OrderStr = $"{prop} {order.Replace("ending", "")}";
                }

                var queryParam = new
                {
                    CustomName,
                    Company,
                    Province,
                    City,
                    ChannelCreator,
                    PricipalName,
                    SourceType,
                    Source,
                    ChannelType,
                    Importance,
                    Rate,
                    FollowFrequency,
                    PageSize,
                    PageIndex,
                    OrderStr
                };

                var data = _channelRepository.GetPaginList(queryParam);

                var totalCount = _channelRepository.GetTotalCount(queryParam).FirstOrDefault();

                //var newData = data.Where(d => d.RowId > ((PageIndex - 1) * PageSize) && d.RowId <= PageSize * PageIndex);

                var result = new
                {
                    pageSize = PageSize,
                    pageIndex = PageIndex,
                    totalCount = totalCount,
                    data = data
                };
                return Json(result);

            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        [HttpGet("exprotchannel")]
        public JsonResult GetChannelExprot(
            string CustomName,
            string Company,
            string Province,
            string City,
            string ChannelCreator,
            string PricipalName,
            string SourceType,
            string Source,
            string ChannelType,
            int? Importance,
            int? Rate,
            string FollowFrequency)
        {
            try
            {
                var queryParam = new
                {
                    CustomName,
                    Company,
                    Province,
                    City,
                    ChannelCreator,
                    PricipalName,
                    SourceType,
                    Source,
                    ChannelType,
                    Importance,
                    Rate,
                    FollowFrequency
                };

                var data = _channelRepository.GetExportChannel(queryParam).OrderByDescending(d => d.Id);

                var baseInfoTittle = new string[] { "'姓名'", "'渠道创建人'", "'单位名称'", "'所在部门'", "'职位'" };
                var baseInfoField = new string[]
                    {"'CustomName'", "'ChannelCreator'", "'Company'", "'Department'", "'Position'"};

                var normalInfoTitle = new string[] { "'公司简介'", "'电话'", "'电子邮件'", "'传真'", "'网址'", "'省份'", "'地市'", "'地址'" };
                var normalInfoField = new string[] { "'Hypro'", "'Tel'", "'Email'", "'Fax'", "'Website'", "'Province'", "'City'", "'Address'" };

                var valueInfoTitle = new string[]
                    {"'渠道认识途径'", "'认识途径备注'", "'渠道类别'", "'能力覆盖范围'", "'渠道合作兴趣点'", "'双方合作共赢点'", "'渠道价值'"};
                var valueInfoField = new string[]
                {
                    "'SourceType'", "'Source'", "'ChannelType'", "'ChannelRegion'", "'Inmark'", "'WinWin'",
                    "'Importance'"
                };

                var followInfoTitle = new string[] { "'跟进人'", "'联系频度建议'", "'维系状态'", "'远程沟通记录'", "'拜访记录'", "'更新时间'" };
                var followInfoField = new string[]
                {
                    "'PricipalName'", "'FollowFrequency'", "'Rate'", "'Telweire'", "'Visitre'", "'LastModificationTime'"
                };

                var titleArray = _unitl.MergerArray(
                    _unitl.MergerArray(_unitl.MergerArray(baseInfoTittle, normalInfoTitle), valueInfoTitle),
                    followInfoTitle);

                var fieldArray = _unitl.MergerArray(
                    _unitl.MergerArray(_unitl.MergerArray(baseInfoField, normalInfoField), valueInfoField),
                    followInfoField);


                JToken titleConfig = JToken.Parse($"[{string.Join(",", titleArray)}]");
                JToken fieldConfig = JToken.Parse($"[{string.Join(",", fieldArray)}]");

                List<string> tempList = new List<string>();

                data.ForEach(e =>
                {
                    var updateTime = e.FollowingTime == null ? e.LastModificationTime : (DateTime)e.FollowingTime;
                    var channelType = e.ChannelType == null ? "" : ((ChannelCategoryEnums)e.ChannelType).ToString();

                    tempList.Add(
                        $"{{CustomName:'{e.Customname}',ChannelCreator:'{e.ChannelCreator}',Company:'{e.Company.Replace(@"\",@"\\")}',Department:'{e.Department}',Position:'{e.Position}'," +
                        $"Hypro:'{e.Hypro}',Tel:'{e.Tel}',Email:'{e.Email}',Fax:'{e.Fax}',Website:'{e.Website}',Province:'{e.Province}',City:'{e.City}',Address:'{e.Address}'," +
                        $"SourceType:'{e.SourceType}',Source:'{e.Source}',ChannelType:'{channelType}',ChannelRegion:'{e.ChannelRegion}',Inmark:'{e.Inmark}',WinWin:'{e.WinWin}',Importance:'{((ChannelImportanceEnums)e.Importance).GetDescription()}'," +
                        $"PricipalName:'{e.Pricipalname}',FollowFrequency:'{e.FollowFrequency}',Rate:'{((ChannelRateEnum)e.Rate).GetDescription()}',Telweire:'{e.Telweire}',Visitre:'{e.Visitre}',LastModificationTime:'{updateTime.ToString("yyyy-MM-dd HH:mm:ss")}'}}");
                });
                JToken exportData = JToken.Parse("[" + string.Join(",", tempList) + "]");
                string resultPath = _unitl.ExportCustomerToExcel(titleConfig, fieldConfig, exportData, "渠道信息表_");
                var rootUrl = HttpContext.Request.Host.Value; // + "/Results";

                resultPath = resultPath.Replace(_hostingEnvironment.ContentRootPath, "").ToHttpStylePath();

                var resultUrl = $"{rootUrl}{resultPath}"; // string.Format("{0}{1}", rootUrl, resultPath);

                return Json(resultUrl);
            }
            catch (Exception ex)
            {
                return Json(ex, success: false);
            }
        }

        [HttpGet("GetChannelById")]
        public JsonResult GetChannelById(int id)
        {
            try
            {
                var data = _channelRepository.GetChannelById(new { id });
                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        [HttpPost]
        public JsonResult PostChannel(Channelinfo model)
        {
            try
            {
                var data = _channelRepository.AddChannel(model);

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }


        [HttpPut]
        public JsonResult PutChannel(Channelinfo model)
        {
            try
            {
                var data = _channelRepository.UpdateChannel(model) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        [HttpPut("updateBaseinfo")]
        public JsonResult PutChannelBase(ChannelBaseinfo model)
        {
            try
            {
                var data = _channelRepository.UpdateChannelBase(model) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        [HttpPut("updateValueinfo")]
        public JsonResult PutChannelValue(ChannelValueinfo model)
        {
            try
            {
                var data = _channelRepository.UpdateChannelValue(model) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }
    }
}
